<?php

/**
 *   OPENSHOP 管理中心品牌管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: brand.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
$exc = new exchange($os->table("brand"), $db, 'brand_id', 'brand_name');

/*------------------------------------------------------ */
//-- 品牌列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
	
	//检查权限
	admin_priv();
		
    $smarty->assign('ur_here',      '商品品牌');
    $smarty->assign('action_link',  array('text' => '添加品牌', 'href' => 'brand.php?act=add'));
    $smarty->assign('full_page',    1);

    $brand_list = get_brandlist();

    $smarty->assign('brand_list',   $brand_list['brand']);
    $smarty->assign('filter',       $brand_list['filter']);
    $smarty->assign('record_count', $brand_list['record_count']);
    $smarty->assign('page_count',   $brand_list['page_count']);
    
    assign_query_info();
    
    $smarty->display('brand_list.tpl');
}

/*------------------------------------------------------ */
//-- 添加品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('add_brand');

    $smarty->assign('ur_here',     '添加品牌');
    $smarty->assign('action_link', array('text' => '商品品牌', 'href' => 'brand.php?act=list'));
    $smarty->assign('form_action', 'insert');
    
    $smarty->assign('brand', array('sort_order'=>0, 'is_show'=>1));
    assign_query_info();
    $smarty->display('brand_info.tpl');
}
elseif ($_REQUEST['act'] == 'insert')
{
    /*检查品牌名是否重复*/
    admin_priv('add_brand');

    $is_show = isset($_REQUEST['is_show']) ? intval($_REQUEST['is_show']) : 0;

    $is_only = $exc->is_only('brand_name', $_POST['brand_name']);

    if (!$is_only)
    {
        sys_msg(sprintf('品牌 %s 已经存在！', stripslashes($_POST['brand_name'])), 1);
    }

    /*对描述处理*/
    if (!empty($_POST['brand_desc']))
    {
        $_POST['brand_desc'] = $_POST['brand_desc'];
    }

    $img_name = '';    
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
        $filesync->setting('brand', 'data/brandlogo', FALSE); 
	    $affix_data = $filesync->put_up($_FILES['brand_logo']);
	    if ($affix_data !== false)
	    {
	        $img_name = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
    	$img_name = $filesync->upload_image($_FILES['brand_logo'],'brandlogo');
    }
    
     /*处理URL*/
    $site_url = sanitize_url( $_POST['site_url'] );

    /*插入数据*/

    $sql = "INSERT INTO ".$os->table('brand')."(brand_name, site_url, brand_desc, brand_logo, is_show, sort_order) ".
           "VALUES ('$_POST[brand_name]', '$site_url', '$_POST[brand_desc]', '$img_name', '$is_show', 
           '$_POST[sort_order]')";
    $db->query($sql);

    admin_log($_POST['brand_name'],'add','brand');

    /* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = '继续添加新品牌';
    $link[0]['href'] = 'brand.php?act=add';

    $link[1]['text'] = '返回品牌列表';
    $link[1]['href'] = 'brand.php?act=list';

    sys_msg('新品牌添加成功！', 0, $link);
}

/*------------------------------------------------------ */
//-- 编辑品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    admin_priv('edit_brand');
    
    $sql = "SELECT brand_id, brand_name, site_url, brand_logo, brand_desc, brand_logo, is_show, sort_order ".
            "FROM " .$os->table('brand'). " WHERE brand_id='$_REQUEST[id]'";
    $brand = $db->GetRow($sql);

    $smarty->assign('pre_fetch_img', $_CFG['pre_fetch_img'] );
    $smarty->assign('ur_here',     '编辑品牌记录');
    $smarty->assign('action_link', array('text' => '商品品牌', 'href' => 'brand.php?act=list&' . list_link_postfix()));
    $smarty->assign('brand',       $brand);
    $smarty->assign('form_action', 'updata');
    
    assign_query_info();
    
    $smarty->display('brand_info.tpl');
}
elseif ($_REQUEST['act'] == 'updata')
{
    admin_priv('edit_brand');
    if ($_POST['brand_name'] != $_POST['old_brandname'])
    {
        /*检查品牌名是否相同*/
        $is_only = $exc->is_only('brand_name', $_POST['brand_name'], $_POST['id']);

        if (!$is_only)
        {
            sys_msg(sprintf('品牌 %s 已经存在！', stripslashes($_POST['brand_name'])), 1);
        }
    }

    /*对描述处理*/
    if (!empty($_POST['brand_desc']))
    {
        $_POST['brand_desc'] = $_POST['brand_desc'];
    }

    $is_show = isset($_REQUEST['is_show']) ? intval($_REQUEST['is_show']) : 0;
     /*处理URL*/
    $site_url = sanitize_url( $_POST['site_url'] );

    $img_name = '';    
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
        $filesync->setting('brand', 'data/brandlogo', FALSE); 
        $filesync->set_updata(true, $_POST['id'], 'brand');
	    $affix_data = $filesync->put_up($_FILES['brand_logo']);
	    if ($affix_data !== false)
	    {
	        $img_name = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
    	$img_name = $filesync->upload_image($_FILES['brand_logo'],'brandlogo');
    }
    
    $param = "brand_name = '$_POST[brand_name]',  site_url='$site_url', brand_desc='$_POST[brand_desc]', is_show='$is_show', sort_order='$_POST[sort_order]' ";
    if (!empty($img_name))
    {
        //有图片上传
        $param .= " ,brand_logo = '$img_name'";
    }

    if ($exc->edit($param,  $_POST['id']))
    {
        /* 清除缓存 */
        clear_cache_files();

        admin_log($_POST['brand_name'], 'edit', 'brand');

        $link[0]['text'] = '返回品牌列表';
        $link[0]['href'] = 'brand.php?act=list&' . list_link_postfix();
        $note = vsprintf('品牌 %s 修改成功！', $_POST['brand_name']);
        sys_msg($note, 0, $link);
    }
    else
    {
        die($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑品牌名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_brand_name')
{
    check_authz_json('edit_brand');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

    /* 检查名称是否重复 */
    if ($exc->num("brand_name",$name, $id) != 0)
    {
        make_json_error(sprintf('品牌 %s 已经存在！', $name));
    }
    else
    {
        if ($exc->edit("brand_name = '$name'", $id))
        {
            admin_log($name,'edit','brand');
            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf('品牌 %s 修改失败！', $name));
        }
    }
}

elseif($_REQUEST['act'] == 'add_brand')
{
	check_authz_json('add_brand');
    $brand = empty($_REQUEST['brand']) ? '' : json_str_iconv(trim($_REQUEST['brand']));

    if(brand_exists($brand))
    {
        make_json_error('已存在相同的品牌名称！');
    }
    else
    {
        $sql = "INSERT INTO " . $os->table('brand') . "(brand_name)" .
               "VALUES ( '$brand')";

        $db->query($sql);
        $brand_id = $db->insert_id();

        $arr = array("id"=>$brand_id, "brand"=>$brand);

        make_json_result($arr);
    }
}
/*------------------------------------------------------ */
//-- 编辑排序序号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
    check_authz_json('edit_brand');

    $id     = intval($_POST['id']);
    $order  = intval($_POST['val']);
    $name   = $exc->get_name($id);

    if ($exc->edit("sort_order = '$order'", $id))
    {
        admin_log(addslashes($name),'edit','brand');

        make_json_result($order);
    }
    else
    {
        make_json_error(sprintf('品牌 %s 修改失败！', $name));
    }
}

/*------------------------------------------------------ */
//-- 切换是否显示
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_show')
{
    check_authz_json('edit_brand');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_show='$val'", $id);

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 删除品牌
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('drop_brand');

    $brand_id = intval($_GET['id']);

    /* 删除该品牌的图标 */
    $sql = "SELECT brand_id,brand_logo FROM " .$os->table('brand'). " WHERE brand_id = '$brand_id'";
    $b_row = $db->getRow($sql);
    if ($b_row['brand_id'] > 0)
    {
		if($filesync->sync_type=='ftp'){
		    $filesync->connect();
		    @$filesync->drop($brand_id, 'brand');
		    $filesync->quit();		    		
    	}else{
		    if (!empty($b_row['brand_logo'])){
		        @unlink(SOURCE_PATH . $b_row['brand_logo']);
		    }	    		
    	} 
    	
	    $exc->drop($brand_id);

	    /* 更新商品的品牌编号 */
	    $sql = "UPDATE " .$os->table('goods'). " SET brand_id=0 WHERE brand_id='$brand_id'";
	    $db->query($sql);
    }
    $url = 'brand.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 删除品牌图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_logo')
{
    /* 权限判断 */
    admin_priv('drop_brand');
        
    $brand_id = intval($_GET['id']);
    
    /* 取得logo名称 */
    $sql = "SELECT brand_id,brand_logo FROM " .$os->table('brand'). " WHERE brand_id = '$brand_id'";
    $b_row = $db->getRow($sql);

    if ($b_row['brand_id'] > 0)
    {
		if($filesync->sync_type=='ftp'){
		    $filesync->connect();
		    @$filesync->drop($brand_id, 'brand');
		    $filesync->quit();		    		
    	}else{
 		    if (!empty($b_row['brand_logo'])){
		        @unlink(SOURCE_PATH . $b_row['brand_logo']);
		    }	   		
    	}
		
        $sql = "UPDATE " .$os->table('brand'). " SET brand_logo = '' WHERE brand_id = '$brand_id'";
        $db->query($sql);
    }

    $link= array(array('text' => '重新编辑该品牌', 'href' => 'brand.php?act=edit&id=' . $brand_id), array('text' => '返回列表页面', 'href' => 'brand.php?act=list'));
    sys_msg('删除品牌logo成功', 0, $link);
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $brand_list = get_brandlist();

    $smarty->assign('brand_list',   $brand_list['brand']);
    $smarty->assign('filter',       $brand_list['filter']);
    $smarty->assign('record_count', $brand_list['record_count']);
    $smarty->assign('page_count',   $brand_list['page_count']);

    make_json_result($smarty->fetch('brand_list.tpl'), '',
        array('filter' => $brand_list['filter'], 'page_count' => $brand_list['page_count']));
}

/**
 * 获取品牌列表
 *
 * @access  public
 * @return  array
 */
function get_brandlist()
{
	global $_CFG;

    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('brand');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM ".$GLOBALS['os']->table('brand')." ORDER BY sort_order ASC";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $brand_logo = empty($rows['brand_logo']) ? '' :
            '<a href="'.$rows['site_url'].'" target="_brank"><img src="'.$_CFG['pre_fetch_img'].$rows['brand_logo'].'?108,27" width="108" height="27" border="1" alt="品牌LOGO"/></a>';
        $rows['brand_logo'] = $brand_logo;
        $rows['site_url']   = $site_url;

        $arr[] = $rows;
    }

    return array('brand' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
?>